import { Injectable } from '@nestjs/common';
import {
  AddDifyKnowledgeApiDto,
  EDifyKnowledgeTypeEnum,
} from './dto/add-dify-knowledge-api.dto';

const API = 'http://192.168.12.64/v1';
const API_KEY = 'dataset-rrIvCnDLB15SkCMk9gTcPO2O';
const DATASET_ID = '47a4b52f-7d93-4d11-a725-ee3577ee7d5d';
const COMPONENT_DOCUMENT_ID = 'a6c7f1f5-1d88-44e2-a8d8-b5a805fe30e3';
const TEMPLATE_DOCUMENT_ID = 'dc010fc2-c345-48e2-bf7b-8d9a2613680e';
const KIT_DOCUMENT_ID = 'be3327d6-fa48-49c2-9fd5-e83a9240f31d';

@Injectable()
export class DifyKnowledgeApiService {
  async add(addDifyKnowledgeApiDto: AddDifyKnowledgeApiDto) {
    const domMap = {
      [EDifyKnowledgeTypeEnum.Component]: COMPONENT_DOCUMENT_ID,
      [EDifyKnowledgeTypeEnum.Template]: TEMPLATE_DOCUMENT_ID,
      [EDifyKnowledgeTypeEnum.Kit]: KIT_DOCUMENT_ID,
    };
    const domId = domMap[addDifyKnowledgeApiDto.type];
    const res = await fetch(
      `${API}/datasets/${DATASET_ID}/documents/${domId}/segments`,
      {
        method: 'POST',
        headers: {
          'content-type': 'application/json',
          Authorization: `Bearer ${API_KEY}`,
        },
        body: JSON.stringify({
          segments: [
            {
              content:
                // `# ${addDifyKnowledgeApiDto.name}` +
                // `## ${addDifyKnowledgeApiDto.description ?? '-'}` +
                '```typescript\n' +
                `export type T${addDifyKnowledgeApiDto.name} = {\n` +
                ` type: '${addDifyKnowledgeApiDto.type}',\n` +
                ` name: '${addDifyKnowledgeApiDto.name}',\n` +
                ` description: '${addDifyKnowledgeApiDto.description}',\n` +
                ` id: ${addDifyKnowledgeApiDto.id},\n` +
                `}\n` +
                '```',
            },
          ],
        }),
      },
    );
    const data = await res.json();
    console.log(data);
    return 'This action adds a new difyKnowledgeApi';
  }

  async test() {
    const data = {
      id: 1,
      name: '搜索列表',
      description: '111',
      content: '1',
      deleted: 0,
      createdAt: '9/4/2025 14:51:48',
      type: 'Template',
    };
    const parentUrl = `${API}/datasets/${DATASET_ID}/documents/${KIT_DOCUMENT_ID}/segments`;
    const res = await fetch(parentUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${API_KEY}`,
      },
      redirect: 'follow',
      body: JSON.stringify({
        segments: [
          {
            content: `${data.id} qweqwe12313q`,
          },
        ],
      }),
    });
    const parent = (await res.json()) as { data: Array<{ id: string }> };
    const keys = Object.keys(data);
    for (const key of keys) {
      if (key !== 'id') {
        await fetch(`${parentUrl}/${parent.data[0].id}/child_chunks`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${API_KEY}`,
          },
          redirect: 'follow',
          body: JSON.stringify({
            content: `${key}: ${data[key]}`,
          }),
        });

        console.log(
          key,
          `${parentUrl}/${parent.data[0].id}/child_chunks`,
          JSON.stringify({
            content: `${key}: ${data[key]}`,
          }),
        );
      }
    }
    // console.log(parent);
    return 'This action adds a new difyKnowledgeApi';
  }

  // findAll() {
  //   return `This action returns all difyKnowledgeApi`;
  // }

  // findOne(id: number) {
  //   return `This action returns a #${id} difyKnowledgeApi`;
  // }

  // update(id: number, updateDifyKnowledgeApiDto: UpdateDifyKnowledgeApiDto) {
  //   return `This action updates a #${id} difyKnowledgeApi`;
  // }

  // remove(id: number) {
  //   return `This action removes a #${id} difyKnowledgeApi`;
  // }
}
